<?php
namespace App\Http\Logic;

use App\Http\Service\CategoryService;
use App\Models\Category;
use App\Models\User;
use Illuminate\Support\Facades\DB;

class CategoryLogic extends BaseLogic
{
	public function __construct()
	{
		parent::__construct();
	}

	public function index($request)
    {
        $field = ['id', 'category_name', 'sort', 'card_num', 'wait_card_num'];
        $result = CategoryService::service()->getCategoryList(['user_id' => $this->user->id], $request['offset'], $request['pageSize'], $field);
        return $this->handlePageList($result->toArray(), $request['page'], $request['pageSize']);
    }

	public function store($request)
    {
        // 校验名称
        if (CategoryService::service()->getOneByUserIdCategoryName($this->user->id, $request['category_name'])) {
            $this->throwNewInvalidException('笔记本名称不允许重复', 422);
        }

        // 新增
        $count = CategoryService::service()->getCountByUserId($this->user->id);
        if ($count < 1) {
            $this->throwNewInvalidException('还未生成默认笔记本,不允许操作', 422);
        }
        $request['sort'] = $count;
        $result = $this->user->category()->create($request);
        return [
            'id' => $result->id,
            'category_name' => $result->category_name,
            'sort' => $result->sort,
            'card_num' => 0,
            'wait_card_num' => 0
        ];

    }

    public function update($id, $request)
    {
        if (!$old = CategoryService::service()->getOneByIdUserId($id, $this->user->id)) {
            $this->throwNewInvalidException('不被允许的操作', 422);
        }

        if ($old->category_name == Category::CATEGORY_DEFAULT_NAME) {
            $this->throwNewInvalidException('默认笔记本不允许编辑', 422);
        }

        if ($old->category_name == $request['category_name']) {
            return true;
        }

        if (CategoryService::service()->getOneByUserIdCategoryName($this->user->id, $request['category_name'])) {
            $this->throwNewInvalidException('当前笔记本下已有相同名称,请换一个试试...', 422);
        }

        return $old->update(['category_name' => $request['category_name']]);
    }

    /**
     * 变更排序
     * @param $id
     * @param $request
     * @return bool
     * @throws \Throwable
     */
    public function sort($id, $request)
    {
        // 获取当前分类信息
        $category = CategoryService::service()->getOneByIdUserId($id, $this->user->id, ['id', 'category_name', 'sort']);

        if (empty($category)) {
            return false;
        }

        if ($category->sort == 0) {
            $this->throwNewInvalidException('默认的笔记本不允许修改排序',422);
        }

        if ($category->sort == $request['target_sort']) {
            return true;
        }

        DB::beginTransaction();
        try {
            if ($category->sort < $request['target_sort']) {//如果原排序比目标排序小 往后排
                $where = [
                    ['sort','<=',$request['target_sort']],
                    ['sort','>',$category->sort]
                ];
                Category::where($where)->decrement('sort');
            } else {//原排序比目标排序大  往前排
                $where = [
                    ['sort','>=',$request['target_sort']],
                    ['sort','<',$category->sort]
                ];
                Category::where($where)->increment('sort');
            }

            $category->sort = $request['target_sort'];
            $category->save();
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            throw new \Exception('变更失败');
        }

        return true;
    }
}
